package com.example.conf;

import java.util.List;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Optional;
import com.google.common.base.Predicate;

import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 *
 * @author changwei
 * @date 2019年10月21日
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

	@Autowired
	private BeanFactory beanFactory;
	
	@Bean
	public Docket api() {
		List<String> scans = AutoConfigurationPackages.get(beanFactory);
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(new Predicate<RequestHandler>() {
				      @Override
				      public boolean apply(RequestHandler input) {
				    	  boolean myProjectCode = scans.stream().anyMatch(pkg -> {
				    		  return RequestHandlerSelectors.basePackage(pkg).apply(input);
				    	  });
				    	  Optional<ResponseBody> methodBody = input.findAnnotation(ResponseBody.class);
				    	  Optional<ResponseBody> controllerBody = input.findControllerAnnotation(ResponseBody.class);
				    	  return myProjectCode && (methodBody.isPresent() || controllerBody.isPresent());
				      }
				})
				.paths(PathSelectors.any())
				.build();
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("xx系统标题")
				.description("描述")
				.version("1.0")
				.build();
	}
}